package com.yutons.encrypt.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import com.yutons.encrypt.config.MpEncryptProperties;

/**
 * @Title 国密算法SM4
 * @Author yutons
 * @Date 2024-06-19 16:31
 * @Desc
 */
public class SM4Util {

	public static void main(String[] args) {
		String ss = "test123";
		MpEncryptProperties.SecretKey secretKey = new MpEncryptProperties.SecretKey();
		secretKey.setKey("sdafsdscsdafsds1");
		secretKey.setIv("sdafsdscsdafsds1");
		String encode = encode(ss, secretKey);
		System.out.println(encode);
		String decode = decode("LZ5AL1XkcLEwpHiumN9eTQ==", secretKey);
		System.out.println(decode);
	}

	public static String encode(String plainText, MpEncryptProperties.SecretKey secretKey) {
		return encrypt(plainText, secretKey.getKey(), secretKey.getIv());
	}

	public static String decode(String cipherText, MpEncryptProperties.SecretKey secretKey) {
		return decrypt(cipherText, secretKey.getKey(), secretKey.getIv());
	}

	public static String encrypt(String plainText, String key, String iv) {
		SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
		String value = null;
		try {
			value = sm4.encryptHex(plainText);
		} catch (Exception e) {
			value = plainText;
		}
		return value;
	}

	public static String decrypt(String cipherText, String key, String iv) {
		SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
		String value = null;
		try {
			value = sm4.decryptStr(cipherText);
		} catch (Exception e) {
			value = cipherText;
		}
		return value;
	}
}
